<template>
  <a-form
    :form="form"
    :label-col="{ span: 5 }"
    :wrapper-col="{ span: 12 }"
    @submit="handleSubmit"
  >
    <a-form-item label="旧密码">
      <a-input
        v-decorator="[
          'oldPassword',
          { rules: [{ required: true, message: '请输入旧密码！' }] },
        ]"
      />
    </a-form-item>
    <a-form-item label="新密码">
      <a-input
        v-decorator="[
          'confirmPsw',
          { rules: [{ required: true, validator: this.checkPsw }] },
        ]"
      />
    </a-form-item>
    <a-form-item label="确认密码">
      <a-input
        v-decorator="[
          'newPassword',
          { rules: [{ required: true, validator: this.confirmPsw }] },
        ]"
      />
    </a-form-item>

    <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
      <a-button type="primary" html-type="submit"> 保存 </a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import { updatePass } from "../../services/dataSource";
export default {
  data() {
    return {
      formLayout: "horizontal",
      form: this.$form.createForm(this, { name: "coordinated" }),
      id: "",
    };
  },
  created() {
    this.id = localStorage.getItem("id");
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          const { oldPassword, newPassword,confirmPsw } = values;
          updatePass(this.id, oldPassword, newPassword,confirmPsw).then((res) => {
            if (res.data.success) {
              this.$message.success("保存成功！");
            } else {
              this.$message.error("保存错误，请联系管理员");
            }
          });
        }
      });
    },
    checkPsw(rule, value, callback) {
      if (value) {
        var datas = this.form.getFieldsValue();
        if (value == datas.oldPassword) {
          callback("新密码不能与原始密码相同");
        } else if (value != datas.confirmPsw && datas.confirmPsw) {
          callback("两次密码输入不一致");
        } else {
          callback();
        }
      } else {
        callback("两次密码输入不一致");
      }
    },
    confirmPsw(rule,value,callback){
      if (value) {
            var datas = this.form.getFieldsValue();
            if (value != datas.confirmPsw) {
                callback('两次密码输入不一致');
            } else {
                callback();
            }
        }
        callback();
    }
  },
};
</script>